const path = require('path');
const fse = require('fs-extra');
const mime = require('mime');
const ejs = require('ejs');


const defaultRender = async (content, data) => {

    let pageContent = '';
    
    try {
        pageContent = ejs.render(content, data); 
    }
    catch(e) {
        pageContent = JSON.stringify(e);
    }
    
    return pageContent;

}

module.exports = (config, util) => {

    return async (ctx, next) => {
        
        ctx.render = async function(templatePath) {
            const url = templatePath ? templatePath : ctx.url;
            const ext = path.extname(url);
            const root = config.root;
            const {
                templateExtension,
                engine,
                templateData
            } = config;
            const filePath = path.join(root, url);
    
            let isExist = util.isPathExist(filePath);

            if(isExist && templateExtension.includes(ext)) {
                let data = templateData[url] || {};
                let content = fse.readFileSync(filePath, {
                    encoding: 'utf-8'
                });
    
                if (typeof data === 'function') {
                    data = await data(ctx);
                }
    
                if (engine && typeof engine.render === 'function') {
                    content = await engine.render(content, data);
                } 
                else {
                    content = await defaultRender(content, data);
                }

                ctx.contentType = mime.getType('html');
                ctx.body = content;
            }
            else {
                await next();
            }    
        }

        await ctx.render();
    }

}